/*
 * urlFile.cc
 *
 *  Created on: Apr 30, 2011
 *      Author: xrose
 */

#include "urlFile.h"

urlFile::urlFile():_url(), _curPos(0), _size(0), _isOpen(false), _diskFile(){};
urlFile::urlFile(Url url):_url(url), _curPos(0), _isOpen(false), _diskFile(){
	string _tmpname = _url.getIdentifier();
	//_filename = _url.getIdentifier();
	_filename = Util::SplitFilename(_tmpname);
	cout<<"DEBUG: ...urlFile::urlFile(Url):_filename = "<<_filename<<endl;
	_size = findFileSize();
	cout<<"DEBUG: ...urlFile::urlFile(Url):_filesize = "<<_size<<endl;
	cout<<"DEBUG: ___urlFile::urlFile(Url)"<<endl;
}
urlFile::urlFile(Url url, string filename):_filename(filename), _url(url), _curPos(0), _isOpen(false), _diskFile(){
	_size = findFileSize();
}
urlFile::~urlFile(){
	if(_isOpen) close();
}
unsigned long urlFile::findFileSize(){
	cout<<"DEBUG: ...urlFile::findFileSize()"<<endl;
	httpConnections	con(101, _url);
	bool status;
	string str_head = con.getHead();
	if(str_head.size()==0){
		con.close();
		return 0;
	}
	status=con.close(); //close the connection
	//parse header
	char *cont_len_pos;
	unsigned long cont_len;
	const char *header = str_head.c_str();
	cout<<"DEBUG: urlFile::findFileSize()::str_head = "<<str_head<<endl;
	cont_len_pos=(char*)strstr(header, "Content-Length:");
	cont_len_pos=(char*)strchr(cont_len_pos, ' ');
	cont_len_pos++;
	sscanf(cont_len_pos, "%ld", &cont_len);
	cout<<"DEBUG: ___urlFile::findFileSize()"<<endl;
	return cont_len;
}
unsigned long urlFile::getSize(){
	return _size;
}
bool urlFile::isOpen(){
	return _isOpen;
}
bool urlFile::open(){
	cout<<"DEBUG: ...urlFile::open()"<<endl;
	cout<<"DEBUG: ...urlFile::open():_filename = "<<_filename<<endl;
	if(_size==0)return false;
	_diskFile.open(_filename.c_str(), ios::out);
	//ensure enought disk space
	_diskFile.seekp(_size - 1);
	_diskFile.write("\0", 1);
	_diskFile.seekp(0);

	_isOpen=true;
	return true;
}
bool urlFile::close(){
	if(_isOpen){
		_diskFile.close();
		_isOpen=false;
		return true;
	}
	return false;
}
long urlFile::write(thrdStruct &rec){
	long numOfByteToWrite = rec.getDlStatus();
	if(numOfByteToWrite>0){
		_curPos=rec.getFilePos();
		_diskFile.seekp(_curPos);
		_diskFile.write(rec.buffer, numOfByteToWrite);
		rec.setFilePos(_diskFile.tellp());
		rec.setDlStatus(0);
	}
	return numOfByteToWrite;
}
